/* Quiz Manager - Create and edit web quizzes.
 * Copyright (C) 2008  Alexis Brunet, Jean-Michel Brunet, Enrique Hotes, Carlo Russo
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package soen343.domain;

import java.sql.ResultSet;
import java.sql.SQLException;

import soen343.data.QuestionTDG;
import soen343.data.MultipleChoiceQuestionTDG;

public class MultipleChoiceQuestionMapper {
	private final static int QUESTION_TYPE = QuestionFactory.MULTIPLE_CHOICE;
	
	private MultipleChoiceQuestionMapper(){}

	public static void insert( MultipleChoiceQuestion q ) throws Exception{
		try {
			QuestionTDG.insert(q.getQuizId(), QUESTION_TYPE, 1, q.getName(), q.getText());
			ResultSet rs = QuestionTDG.findByName(q.getName());
			rs.first();
			int questionId = rs.getInt("id");
			int choiceId = 1;
			for(String choice : q.getChoices()){
				MultipleChoiceQuestionTDG.insert(questionId,choiceId,choice);
				choiceId++;
			}
		} catch (SQLException e) {
			throw new Exception(e.getMessage());
		}
	}
	
	public static void update( MultipleChoiceQuestion q ){
		try {
			QuestionTDG.update(q.getId(), q.getQuizId(), QUESTION_TYPE, 1, q.getName(), q.getText());
			
			MultipleChoiceQuestionTDG.deleteAllChoices(q.getId());

			//Insert them again
			int choiceId = 1;
			for(String choice : q.getChoices()){
				MultipleChoiceQuestionTDG.insert(q.getId(),choiceId,choice);
				choiceId++;
			}
			
		} catch (SQLException e) {
		}
	}
	
	public static void delete( MultipleChoiceQuestion q ){
		try {
			MultipleChoiceQuestionTDG.deleteAllChoices(q.getId());
			QuestionTDG.delete(q.getId());
		} catch (SQLException e) {
		}
	}
	
}
